package com.search.api.controller;

import com.search.api.dto.FileDo;
import com.search.api.dto.ReturnDo;
import com.search.api.dto.SearchDo;
import com.search.api.service.ViewFileService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Objects;

/**
 * @author huej
 * @description todo
 * @date 2021/7/14 6:54 下午
 */
@RestController
public class IndexController {
    private final ViewFileService viewFileService;

    /**
     * 构造方法
     *
     * @param viewFileService 文件搜索实现类
     */
    public IndexController(ViewFileService viewFileService) {
        this.viewFileService = viewFileService;
    }

    @RequestMapping("viewFile.do")
    public ReturnDo viewFile(SearchDo searchDO) throws Exception {
        return viewFileService.viewFile(searchDO);
    }


    /**
     * 文件路径下文件路径
     *
     * @param searchDo 文件路径
     * @return 入参下的文件路径
     */
    @RequestMapping("viewPath.do")
    public ReturnDo viewPath(SearchDo searchDo) {
        ReturnDo returnDo = new ReturnDo();
        File file = new File(searchDo.getFilePath());

        if (file.exists()) {
            if (file.isFile() || Objects.requireNonNull(file.list()).length == 0) {
                FileDo fileDo = new FileDo();
                fileDo.setFilePath(searchDo.getFilePath());
                returnDo.getFileDos().add(fileDo);
            } else {
                for (String path : Objects.requireNonNull(file.list())) {
                    FileDo fileDo = new FileDo();
                    if (searchDo.getFilePath().endsWith(File.separator)) {
                        fileDo.setFilePath(searchDo.getFilePath() + path);
                    } else {
                        fileDo.setFilePath(searchDo.getFilePath() + File.separator + path);
                    }
                    returnDo.getFileDos().add(fileDo);
                }
            }
        }
        return returnDo;
    }
}
